<template>
  <div class="app-main-container">
    <div class="app-main-title">{{ copName }} <div class="goback" @click="$router.replace(`/vipCardList/vipCardList`)">
      <i class="el-icon-refresh-left" /> 返回上一页
    </div></div>
    <div>
      <el-form ref="form" class="doumee-form" :model="param" label-width="150px" label-suffix="：" :rules="rules">
        <div class="property-title">会员卡属性</div>
        <el-form-item label="会员卡名称" prop="cardName">
          <el-input v-model="param.cardName" maxlength="6" placeholder="请输入会员卡名称" style="width: 400px" />
          <span class="placeholder9 ml20">会员卡名称最多六个字</span>
        </el-form-item>
        <el-form-item label="卡样" class="select-style" prop="avatar" :rules="{ required: true, message: param.cardCode == 'cardZero' ? '请上传卡样':'请选择卡样', trigger: 'change' }">
          <el-radio-group v-model="param.cardCode" @change="changeType">
            <el-radio v-for="(item, index) in memberImgList" :key="index" :label="item.code">{{ item.remaks }}</el-radio>
          </el-radio-group>
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="CARD_TYPE_IMG"
              :fixed-number="[69, 34]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="upload-wrap">
            <el-upload
              v-if="param.cardCode == 'cardZero'"
              class="device-uploader"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              accept=".jpg,.png,.jpeg"
              :auto-upload="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div v-if="!param.showAvatar" style="color: #999999;font-size: 14px;line-height: 20px;">上传图片</div>
              <div
                v-show="param.showAvatar"
                class="file"
                :style="'background-image: url(' + param.showAvatar + ')'"
              >
                <div class="delete">
                  <i class="el-icon-delete icon" @click.stop="deleteImage" />
                </div>
              </div>
            </el-upload>
            <div v-if="param.cardCode == 'cardZero'" class="placeholader tip-style">
              <div style="color: #333333;">建议尺寸：690px*334px</div>
              <div>支持png、jpg、jpeg格式，大小不超过2M，上传图片不允许涉及政治敏感与色情</div>
            </div>
          </div>
          <el-image
            v-if="param.cardCode != 'cardZero' && param.showAvatar"
            style="width: 174px; height: 84px"
            :src="param.showAvatar"
            :preview-src-list="[param.showAvatar]"
          />
        </el-form-item>
        <el-form-item label="销售渠道" prop="channelList">
          <el-checkbox-group v-model="param.channelList">
            <el-checkbox label="微信端" />
            <el-checkbox label="场馆端" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="默认开卡">
          <el-switch
            v-model="isNormal"
            active-color="#435EBE"
            inactive-color="#999999"
          />
          <span class="tip-style">开启后，会员注册时，默认为当前会员卡类型；只能有一个默认会员卡</span>
        </el-form-item>
        <el-form-item label="等级">
          <el-input v-model="param.level" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请设置会员卡等级(数值越大，等级越高，不传默认最低)" style="width: 400px" />
          <span class="tip-style">请设置会员卡等级，数值越大，等级越高，不填写默认最低等级</span>
        </el-form-item>

        <div class="line-style" />

        <div class="property-title">规则设置</div>

        <el-form-item label="首充最低金额" prop="price" class="discount-style">
          <el-input v-model="param.price" oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')" placeholder="请输入首充最低金额" />
        </el-form-item>
        <el-form-item label="续充最低金额" prop="continuedPrice" class="discount-style">
          <el-input v-model="param.continuedPrice" oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')" placeholder="请输入续充最低金额" />
        </el-form-item>
        <el-form-item label="自动升级卡">
          <el-switch
            v-model="upgrade"
            active-color="#435EBE"
            inactive-color="#999999"
          />
          <span class="tip-style">会员达到累计充值/累计消费金额时，自动升级为当前会员卡类型</span>
        </el-form-item>
        <el-form-item v-if="upgrade" label="累计充值升级金额" prop="totalMoney">
          <el-input v-model="param.totalMoney" oninput="value=value.replace(/[^0-9]{0,1}(\d*(?:\.\d{0,2})?).*$/g, '$1')" placeholder="请输入累计充值升级金额" style="width: 400px" />
        </el-form-item>

        <div class="line-style" />

        <div class="property-title">折扣信息配置 <span class="tip-style">请输入会员卡默认折扣0-1之间两位小数，</span></div>

        <el-form-item v-for="(item, index) in param.discounts" :key="index" :label="item.discountTypeName" :prop="`discounts[${index}].discount`" :rules="{ required: true, message: '请输入商品折扣', trigger: 'blur' }" class="discount-style">
          <el-input
            v-model="item.discount"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            placeholder="请输入商品折扣，0-1直接两位小数，例如0.1表示1折"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-preventReClick type="primary" :loading="loading" @click="onSubmit('form')">提交</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { addCard, cardDetail, updateCard, uploadFile, discountType, mrMemberImg } from '@/api'
import Cropper from '@/components/cropper'
// import { getList } from '@/api/table'
export default {
  components: {
    Cropper
  },
  data() {
    return {
      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      copName: '新增会员卡',
      avatarStyle: 0,
      avatarStyles: [],
      channelList: [],
      upgrade: false,
      loading: false,
      isNormal: false,
      imageList: [],
      uploadFileUrl: uploadFile,
      dialogVisible: false,
      memberImgList: [],
      uploadParam: {
        // folder: 'PUBLIC_IMG'
        folder: 'CARD_TYPE_IMG'
      },
      param: {
        channelList: [],
        discounts: [
          {
            discount: '',
            discountType: '10',
            id: ''
          },
          {
            discount: '',
            discountType: '20',
            id: ''
          },
          {
            discount: '',
            discountType: '30',
            id: ''
          },
          {
            discount: '',
            discountType: '40',
            id: ''
          }
        ],
        isnormal: '',
        price: '',
        totalMoney: '',
        cardName: '',
        upgrade: ''
      },
      rules: {
        cardName: [
          { required: true, message: '请输入会员卡名称', trigger: 'blur' }
        ],
        simpleName: [
          { required: true, message: '请输入场馆简称', trigger: 'blur' }
        ],
        channelList: [
          { required: true, message: '请选择销售渠道', trigger: 'change' }
        ],
        avatar: [
          { required: true, message: '请上传卡样', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入首充最低金额', trigger: 'blur' }
          // { pattern:
          //     /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额必须大于0', trigger: 'blur' }
        ],
        continuedPrice: [
          { required: true, message: '请输入续充最低金额', trigger: 'blur' }
          // { pattern:
          //     /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额必须大于0', trigger: 'blur' }
        ],
        totalMoney: [
          { required: true, message: '请输入累计充值升级金额', trigger: 'blur' },
          { pattern:
              /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '金额必须大于0', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.query.id) {
      this.copName = '编辑会员卡'
      this.getCardDetail(this.$route.query.id)
    } else {
      this.getStyle()
    }
    this.getMrMemberImg()
  },
  methods: {
    // 默认卡样式
    getMrMemberImg() {
      mrMemberImg({ param: {}}).then(res => {
        if (res.errorCode === '000000') {
          this.memberImgList = res.recordList || []
          if (!this.$route.query.id && this.memberImgList.length > 0) {
            this.$set(this.param, 'cardCode', res.recordList[0].code)
            this.$set(this.param, 'avatar', res.recordList[0].pic)
            this.$set(this.param, 'showAvatar', res.recordList[0].showPic)
          }
        }
      })
    },
    getStyle() {
      discountType({
        param: {},
        userId: sessionStorage.getItem('userId')
      }).then(res => {
        console.log(res)
        this.param.discounts = res.recordList
        const oldDiscount = this.param.discounts
        for (let index = 0; index < 4; index++) {
          for (var j = 0; j < 3; j++) {
            if (parseInt(oldDiscount[j].discountType) > parseInt(oldDiscount[j + 1].discountType)) {
              var temp = oldDiscount[j]
              oldDiscount[j] = oldDiscount[j + 1]
              oldDiscount[j + 1] = temp
            }
          }
        }
        this.param.discounts = oldDiscount
      }).catch(err => {
        console.log(err)
      })
    },
    getCardDetail(id) {
      cardDetail({
        param: { id: id },
        userId: sessionStorage.getItem('userId')
      }).then(res => {
        this.param = res.record
        console.log(this.param)
        switch (this.param.channel) {
          case '1_1':
            this.$set(this.param, 'channelList', ['微信端', '场馆端'])
            break
          case '0_1':
            this.$set(this.param, 'channelList', ['场馆端'])
            break
          case '1_0':
            this.$set(this.param, 'channelList', ['微信端'])
            break
          default:
            break
        }
        this.upgrade = this.param.upgrade === '1'
        this.isNormal = this.param.isnormal === '1'

        this.imageList.push({
          url: this.param.showAvatar,
          response: {
            insertUrl: this.param.avatar,
            showUrl: this.param.showAvatar
          }
        })
        if (!this.param.discounts.length) {
          // 添加折扣
          for (let index = 0; index < 4; index++) {
            this.param.discounts.push({
              discount: '',
              discountType: (10 * (index + 1)).toString(),
              id: ''
            })
          }
        } else {
          // 折扣排序
          const oldDiscount = this.param.discounts
          for (let index = 0; index < 4; index++) {
            for (var j = 0; j < 3; j++) {
              if (parseInt(oldDiscount[j].discountType) > parseInt(oldDiscount[j + 1].discountType)) {
                var temp = oldDiscount[j]
                oldDiscount[j] = oldDiscount[j + 1]
                oldDiscount[j + 1] = temp
              }
            }
          }
          this.param.discounts = oldDiscount
          console.log(this.param.discounts)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.$set(this.param, 'avatar', res.insertUrl)
      this.$set(this.param, 'showAvatar', res.showUrl)
      this.$refs.form.clearValidate()
    },
    changeType(e) {
      if (e === 'cardZero') {
        this.$set(this.param, 'avatar', '')
        this.$set(this.param, 'showAvatar', '')
      } else {
        const arr = this.memberImgList
        arr.forEach(s => {
          if (s.code === e) {
            this.$set(this.param, 'avatar', s.pic)
            this.$set(this.param, 'showAvatar', s.showPic)
          }
        })
      }
      this.$refs.form.clearValidate()
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'showAvatar', config.showUrl)
        this.$set(this.param, 'avatar', config.insertUrl)
        this.dialogCropperVisible = false
        this.$refs.form.clearValidate()
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除头像
    deleteImage() {
      this.$set(this.param, 'avatar', '')
      this.$set(this.param, 'showAvatar', '')
    },
    remoImageUrl(file, fileList) {
      console.log(file, fileList)
      this.$set(this.param, 'avatar', '')
      this.$set(this.param, 'showAvatar', '')
    },
    onSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.loading = true
          switch (that.param.channelList.length) {
            case 0:
              that.$message.error('至少选择一种销售渠道')
              return
            case 1:
              if (that.param.channelList[0] === '微信端') {
                that.param.channel = '1_0'
              } else {
                that.param.channel = '0_1'
              }
              break
            case 2:
              that.param.channel = '1_1'
              break
            default:
              break
          }
          that.param.isnormal = that.isNormal ? '1' : '0'
          that.param.continuedPrice = parseFloat(that.param.continuedPrice)
          that.param.upgrade = that.upgrade ? '1' : '0'
          if (that.upgrade) {
            that.param.totalMoney = parseFloat(that.param.totalMoney)
          }
          const dcArr = that.param.discounts
          dcArr.forEach(temp => {
            temp.discount = parseFloat(temp.discount)
          })
          that.param.discounts = dcArr
          if (that.$route.query.id) {
            const p = that.param
            p.id = that.$route.query.id
            updateCard({ param: p }).then(res => {
              that.loading = false
              if (res.errorCode === '000000') {
                console.log(res.errorMsg)
                that.$message.success('保存成功!')
                that.$router.replace(`/vipCardList/vipCardList?renovate=1`)
              }
            }).catch(er => {
              that.loading = false
              console.log(er)
            })
          } else {
            addCard({ param: that.param }).then(res => {
              this.loading = false
              if (res.errorCode === '000000') {
                console.log(res.errorMsg)
                that.$message.success('增加成功!')
                that.$router.replace(`/vipCardList/vipCardList?renovate=1`)
              }
            }).catch(er => {
              this.loading = false
              console.log(er)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 174px;
  height: 84px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
  .select-style{
    vertical-align: middle;
  }
  .upload-style {
    vertical-align: middle;
    display: inline-block;
    border: none;
    position: relative;
    .deleget {
      position: absolute;
      right: 0px;
    }
  }

  .img-style {
    margin: auto;
    background-color: #eee;
    width: 100px;
    height: 60px;
    vertical-align: middle;
  }
  .avatar{
    width: 148px;
    height: 148px;
    display: block;
  }
  .line-style {
    background-color: #DFE2E8;
    height: 1px;
    // width: 80%;
    // margin: 0 auto;
    margin-bottom: 20px;
  }
  .discount-style {
    width: 50%;
    display: inline-block;
  }
  .upload-wrap{
  display: flex;
  align-items: center;
  .placeholader{
    flex: 1;
    div{
     line-height: 20px;
    }
  }
}
</style>
